<template>
  <el-row style="width: 100%; min-width: 900px; margin: 0px 5% 0px 6%">
    <el-col :span="18" class="main-content">
      <div class="card-container">
        <el-card style="width: 100%">
          <!-- 标题显示 -->
          <template #header>
            <div class="card-header">
              <span>{{ blogInfo.blogTitle }}</span>
            </div>
          </template>
          <!-- 文章基本信息 -->
          <div class="blog-info-container">
            <div class="blog-meta">
              <div class="author-info">
                <el-avatar :size="40" :src="blogInfo.avatar || '/default-avatar.png'" />
                <div class="author-detail">
                  <div class="author-name">
                    {{ blogInfo.author }}
                  </div>
                  <div class="publish-time">
                    <svg-icon icon-class="remind" :size="20" />
                    {{ blogInfo.publishTime }}
                  </div>
                </div>
              </div>
              <div class="blog-stats">
                <div class="stat-item">
                  <svg-icon icon-class="view" :size="20" />
                  <span>{{ blogInfo.blogViews }} 阅读</span>
                </div>
                <div class="stat-item">
                  <svg-icon icon-class="appreciate" :size="20" />
                  <span>{{ blogInfo.likes }} 点赞</span>
                </div>
                <div class="stat-item">
                  <svg-icon icon-class="message" :size="20" />
                  <span>{{ blogInfo.commentCount || 0 }} 评论</span>
                </div>
              </div>
            </div>
            <div class="blog-tags">
              <el-tag
                v-for="tag in blogInfo.blogTags"
                :key="tag"
                class="blog-tag"
                effect="light"
                round
              >
                <svg-icon icon-class="read" :size="20" />
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <!-- 简介信息统计栏 -->
          <!-- <el-row>
            <el-col :span='24'>
              <quick-section />
            </el-col>
          </el-row> -->
          <!-- 滚动信息栏 -->
          <el-row>
            <el-col :span="24">
              <u-notice-bar vertical :data="noticeList" />
            </el-col>
          </el-row>
          <el-divider content-position="center">正文</el-divider>
          <!-- 博客内容栏 -->
          <el-row>
            <el-col :span="24" class="preview-col">
              <el-scrollbar id="preview-container" ref="scrollbarRef" height="1000px">
                <iz-preview-content :editor-id="editorId" :model-value="blogInfo.blogContent" />
              </el-scrollbar>
            </el-col>
          </el-row>
        </el-card>

        <el-divider />

        <!-- 文章操作行（纵向悬浮工具栏） -->
        <toolbar
          :is-followed="isFollowed"
          :likes="blogInfo.likes"
          @follow="handleFollow"
          @unfollow="handleUnfollow"
          @like="handleLike"
          @dislike="handleDislike"
          @collect="handleCollect"
          @open-comment-drawer="openCommentDrawer"
          @report="handleReport"
        />

        <el-card class="comment-summary-card overflow-hidden border-none shadow-lg">
          <template #header>
            <div class="card-header">
              <span>热门评论</span>
            </div>
          </template>
          <div v-if="hottestComment">
            <div class="flex items-center mb-4 relative z-10">
              <el-avatar
                :size="40"
                :src="hottestComment.user?.avatar || '/default-avatar.png'"
                class="border-2 border-white shadow-sm"
              />
              <div class="ml-3">
                <div class="flex items-center">
                  <span class="username font-semibold text-gray-900">
                    {{ hottestComment.user?.username || '匿名用户' }}
                  </span>
                  <span class="ml-2 text-yellow-500 text-xl">🔥</span>
                </div>
                <div class="text-xs text-gray-500 mt-0.5">
                  {{ hottestComment.createTime ? formatDate(hottestComment.createTime) : '' }}
                </div>
              </div>
            </div>

            <p class="text-gray-700 leading-relaxed mb-4 relative z-10">
              {{ hottestComment.content }}
            </p>

            <!-- 添加点赞和回复操作按钮 -->
            <div class="flex items-center justify-between relative z-10">
              <div class="flex items-center space-x-4">
                <el-button
                  size="small"
                  type="text"
                  class="flex items-center !text-gray-600 hover:!text-orange-500"
                  @click="handleCommentLike(hottestComment.commentId)"
                >
                  <svg-icon
                    icon-class="appreciate"
                    :size="16"
                    :class="{ '!text-orange-500': hottestComment.liked }"
                  />
                  <span class="ml-1">{{ hottestComment.likes || 0 }}</span>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 评论区（抽屉触发） -->
        <el-drawer v-model="commentDrawerVisible" title="评论区" direction="rtl" size="40%">
          <my-comment :blog-id="blogId" />
        </el-drawer>

        <!-- 页脚区域 -->
        <!-- <template #footer>
          </template> -->
        <el-divider />
        <el-card>
          <!-- 评论区 -->
          <!-- <my-comment :blog-id='blogId' /> -->
        </el-card>
      </div>
    </el-col>
    <el-col :span="6" class="main-aside-right">
      <el-card>
        <template #header>
          <div class="card-header">
            <el-text>目录</el-text>
          </div>
        </template>
        <u-anchor :container="anchorContainer" scroll=".el-scrollbar__wrap" />
      </el-card>
      <el-card>
        <template #header>
          <div class="card-header">
            <el-text>热门标签</el-text>
          </div>
        </template>
        <u-search :config="config" style="width: 100%" @submit="submit" />
      </el-card>
      <!-- </el-affix> -->
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import IzPreviewContent from '@/components/common/preview-content/index.vue';
import MyComment from '@/components/common/comment/index.vue';
import toolbar from '@/components/BlogView/Toolbar.vue';
import 'md-editor-v3/lib/style.css';
import { computed, onMounted, ref } from 'vue';
import { UAnchor, UNoticeBar, SearchConfig, USearch } from 'undraw-ui';
import { browseBlog } from '@/api/blog';
import { BlogInfo } from '@/api/blog/types';
import type { CommentPageVO } from '@/api/comment/types';
import { useCommonStore } from '@/store/modules/common';
import { formatDate } from '@/utils/date';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { pageComment } from '@/api/comment';

const route = useRoute();
const CommonStore = useCommonStore();
const blogId = ref<string>(route.params.blogId as string);

const editorId = 'demo-preview';
const blogInfo = ref<BlogInfo & { commentCount?: number }>({
  blogTitle: '',
  blogCoverImage: '',
  blogContent: '',
  blogTags: [],
  author: '',
  avatar: '',
  publishTime: undefined,
  blogViews: 0,
  likes: 0,
  commentCount: 0
});
const anchorContainer = ref('#preview-container');
// const scrollElement = ref('#preview-container');
// const scrollElement = ref(document.documentElement);

// 评论抽屉状态
const commentDrawerVisible = ref(false);
const openCommentDrawer = () => {
  commentDrawerVisible.value = true;
};

// 最热评论
const hottestComment = ref<Partial<
  CommentPageVO & { user?: unknown; floor?: number; createTime?: string }
> | null>(null);
const fetchHottestComment = async () => {
  try {
    const res = await pageComment({
      blogId: Number(blogId.value),
      pageNum: 1,
      pageSize: 1,
      sortField: 'likes',
      asc: false
    });

    if (res.data.list && res.data.list.length > 0) {
      hottestComment.value = {
        ...res.data.list[0],
        floor: 1, // 设置为热门评论的特殊楼层标识
        liked: false // 初始未点赞状态
      };
    }
  } catch (error) {
    console.error('获取热门评论失败:', error);
  }
};

// 处理评论点赞
const handleCommentLike = async (commentId?: number) => {
  if (!commentId || !hottestComment.value) return;

  try {
    // 这里应该调用点赞API
    // await likeComment(commentId);

    if (hottestComment.value.liked) {
      hottestComment.value.likes = (hottestComment.value.likes || 1) - 1;
    } else {
      hottestComment.value.likes = (hottestComment.value.likes || 0) + 1;
    }
    hottestComment.value.liked = !hottestComment.value.liked;

    ElMessage.success(hottestComment.value.liked ? '点赞成功' : '已取消点赞');
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

onMounted(() => {
  browseBlog(blogId.value).then(res => {
    blogInfo.value = res.data as BlogInfo;
  });
  fetchHottestComment();
});

// ==================================滚动通知=========================================
const noticeList = computed(() => CommonStore.noticeList);

// ====================================检索框============================================
const config = ref<SearchConfig>({
  search: '', // 可选输入框默认值
  keywords: ['学习', 'Java', 'Spring', 'SprngBoot', 'SpringCloud'], // 搜索框关键字滚动
  hotSearchList: ['学习', 'Java', 'Spring', 'SprngBoot', 'SpringCloud'] // top10 热门搜索 最多显示10条数据
});

// 检索栏搜索
const submit = (val: string) => {
  console.log(val);
  window.open(`/all?keyword=${val}`);
};
const scrollbarRef = ref();

// 关注逻辑（模拟，后续可接API）
const isFollowed = ref(false);
const handleFollow = () => {
  isFollowed.value = true;
  ElMessage.success('关注成功');
};
const handleUnfollow = () => {
  isFollowed.value = false;
  ElMessage.info('已取消关注');
};
// 点赞
const handleLike = () => {
  blogInfo.value.likes = (blogInfo.value.likes || 0) + 1;
  ElMessage.success('点赞成功');
};
// 踩
const handleDislike = () => {
  ElMessage.info('已踩（仅前端演示）');
};
// 收藏
const handleCollect = () => {
  ElMessage.success('收藏成功（仅前端演示）');
};
// 举报
const handleReport = () => {
  ElMessage.success('举报成功（仅前端演示）');
};
</script>
<style scoped lang="scss">
.main-content {
  padding: 0px;
  width: 100%;
}

.comment-summary-card {
  margin-top: 24px;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  border: none;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.95) 100%);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 12px 28px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  :deep(.el-card__body) {
    padding: 24px;
  }
}

.main-aside-right {
  padding: 0px 10px;
  // min-width: 300px;

  .affix-class {
    width: 100%;
  }

  .el-card {
    margin-bottom: 10px;
    // max-width: 300px;
    // width: 100%;
  }
}

.card-header {
  span {
    font-size: 20px;
    font-weight: bold;
  }
}

.card-container {
  display: flex;
  flex-direction: column;

  :deep(.el-divider--horizontal) {
    margin: 10px 0px;
  }
}

.username {
  transition: color 0.2s;

  &:hover {
    color: var(--el-color-primary);
    cursor: pointer;
  }
}

.comment-summary-card {
  .el-button--text {
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.2s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
  }
}

:deep(.desc-item-label) {
  font-size: 400px;
  background: var(--el-color-success-light-9) !important;
}

// 隐藏u-anchor自带的目录抬头
:deep(.u-anchor .toc-content) {
  padding: 0px;
}
:deep(.u-anchor .toc-content-heading) {
  display: none;
}
:deep(.u-anchor .u-divider) {
  display: none;
}

/* 当窗口宽度小于 900px 时隐藏元素 */
@media (max-width: 900px) {
  .main-content {
    width: 100%;
  }
  .main-aside-right {
    display: none;
  }
}

.blog-info-container {
  padding: 16px 0;

  .blog-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .author-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .author-detail {
        .author-name {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }

        .publish-time {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          color: var(--el-text-color-secondary);

          .el-icon {
            font-size: 14px;
          }
        }
      }
    }

    .blog-stats {
      display: flex;
      gap: 24px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 6px;
        color: var(--el-text-color-secondary);
        font-size: 14px;

        .el-icon {
          font-size: 16px;
        }
      }
    }
  }

  .blog-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .blog-tag {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 0 12px;
      height: 28px;
      font-size: 13px;

      .el-icon {
        font-size: 14px;
      }
    }
  }
}
</style>
